// image模块
export default {
	props: {
		// 可传照片数量
		imageLimit: {
			type: [Number, String],
			default: 9
		},
		// 相机 & 相册
		imageSourceType: {
			type: Array,
			default: () => ['camera', 'album']
		},
		// 压缩 & 原图
		imageSizeType: {
			type: Array,
			default: () => ['compressed']
			// default: () => ['compressed', 'original']
		}
	},
	data() {
		return {
			image: [],
			imageSourceTypeName: {
				camera: '拍照',
				album: '从手机相册选择'
			}
		}
	},
	methods: {
		// 添加图片
		async addImage() {
			if (this.disabled) return;
			if (this.image.length == this.imageLimit) { // 图片已满
				let isContinue = await this.isFull('image');
				if (!isContinue) return;
			}
			if (this.imageSourceType.length == 1) {
				this.chooseImage(this.imageSourceType[0])
			} else {
				uni.showActionSheet({
					itemList: this.imageSourceType.map(item => this.imageSourceTypeName[item]),
					success: res => {
						this.chooseImage(this.imageSourceType[res.tapIndex])
					}
				});
			}
		},
		chooseImage(imageSourceType) {
			uni.chooseImage({
				sourceType: [imageSourceType],
				sizeType: this.imageSizeType,
				count: this.imageLimit - this.image.length,
				success: async data => {
					let header = {
						// 'Content-Type': 'multipart/form-data',
						// 'Cookie': this.$http.sessionId
					};
					if (this.$http.token)
						header[this.$http.token.header] = this.$http.token.token;
					if (this.checkToken) {
						await this.$http.checkToken(header, () => {
							uni.showToast({
								title: '登录信息已失效',
								icon: 'none'
							})
							uni.reLaunch({
								url: '/pages/login/login'
							});
							this.$http.logout();
						})
					}
					uni.showLoading({
						title: '上传中……',
						mask: true
					});
					let arr = data.tempFilePaths;
					for (let i = 0; i < arr.length; i++) {
						let res = await uni.uploadFile({
							url: this.url.replace('$type', 'image'),
							filePath: arr[i],
							// name: 'file',
							header
						});
						if (res[1]?.statusCode == 200) { // 请求成功
							this.image.push({
								previewSrc: arr[i],
								...JSON.parse(res[1].data).message
							})
							if (i == arr.length - 1) {
								uni.hideLoading(); // 上传完毕隐藏loading
							}
						} else {
							uni.hideLoading();
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							});
							break;
						}
					}
					this.change();
				},
				fail: () => {
					if (imageSourceType == 'camera') {
						this.$w.permission('camera')
					} else {
						this.$w.permission('photoLibrary')
					}
				}
			})
		},
		// 预览图片
		previewImage(array, index) {
			uni.previewImage({
				urls: array.map(item => item.previewSrc),
				current: index
			})
		}
	}
}